import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoSocketClient1 {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoSocketClient1(String serverIp,int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            //1.从控制台读取用户输入的信息
            if (!scanner.hasNext()){
                return;
            }
            String request = scanner.next();
            //2.构造请求数据报
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            //3.发送请求数据报
            socket.send(requestPacket);
            //4.接收服务器响应
            DatagramPacket respondPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(respondPacket);
            //5.从服务器读取的数据进行解析并打印
            String response = new String(requestPacket.getData(),0,requestPacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoSocketClient1 udpEchoSocketClient1 = new UdpEchoSocketClient1("127.0.0.1",9090);
        udpEchoSocketClient1.start();
    }
}
